package cn.tradewin.advisor.persist.services.impl;

import java.util.List;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.slf4j.Logger;

import cn.tradewin.advisor.persist.mapper.WbsMapper;
import cn.tradewin.advisor.persist.model.Wbs;
import cn.tradewin.advisor.persist.services.WbsService;

public class WbsServiceImpl implements WbsService {

	private final SqlSessionFactory sqlSessionFactory;
	private final Logger log;
	
	public WbsServiceImpl(SqlSessionFactory sqlSessionFactory, Logger log) {
		this.sqlSessionFactory = sqlSessionFactory;
		this.log = log;
	}
	
	
	@Override
	public List<Wbs> getAllWbses() {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			WbsMapper mapper = session.getMapper(WbsMapper.class);
			return mapper.selectAllWbses();
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}

	@Override
	public List<Wbs> getAllWbses(String owner) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public int addWbs(Wbs wbs) {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			WbsMapper mapper = session.getMapper(WbsMapper.class);
			int count = mapper.insert(wbs);
			if (count < 0) {
				session.rollback();
				throw new RuntimeException("failure add wbs [" + wbs.getId() + "]");
			}
			session.commit();
			return count;
		} catch (Exception e) {
			if (session != null) {
				session.rollback();
			}
			throw new RuntimeException(e.getMessage());
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}

	@Override
	public int updWbs(Wbs wbs) {
		SqlSession session = null;
		try {
			session = sqlSessionFactory.openSession();
			WbsMapper mapper = session.getMapper(WbsMapper.class);
			int count = mapper.updateByPrimaryKey(wbs);
			if (count < 0) {
				session.rollback();
				throw new RuntimeException("failure upd wbs [" + wbs.getId() + "]");
			}
			session.commit();
			return count;
		} catch (Exception e) {
			if (session != null) {
				session.rollback();
			}
			throw new RuntimeException(e.getMessage());
		} finally {
			if (session != null) {
				session.close();
			}
		}
	}
}
